{% extends base.html %} 

{% block head %}
    <link rel="stylesheet" type="text/css" href="/static/lib/codemirror/codemirror.min.css">
    <link rel="stylesheet" type="text/css" href="/static/lib/codemirror/theme/monokai.min.css">
    <script type="text/javascript" src="/static/lib/codemirror/codemirror.min.js"></script>
    <script type="text/javascript" src="/static/lib/codemirror/mode/markdown.js"></script>
    <script type="text/javascript" src="/static/lib/codemirror/keymap/sublime.js"></script>
    <script type="text/javascript" src="/static/lib/csv.js/csv.js"></script>
    <script type="text/javascript" src="/static/lib/marked/marked.js"></script>
    <script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>
    <script type="text/javascript" src="/static/js/upload.js"></script>
    <script type="text/javascript" src="/static/js/marked-ext.js"></script>
    <script type="text/javascript" src="/static/js/editor.js"></script>
    {% include note/component/edit_css.html %}
{% end %} 

{% block body %} 

{% init error = "" %} 
{% init download_csv = False %}

<div class="alert">
    {{error}}
</div>

<div class="grid-card">
    <form id="mainFrame" action="/note/update" enctype="multipart/form-data" method="POST" class="col-md-12">
        <!-- note-edit-header -->
        <div class="col-md-12" id="submit-div">
            <div>
                <span id="fileId" class="hide">{{file.id}}</span>
            </div>
            <div class="grid-title btn-line-height">
                <span>文档编辑器</span>
                <div class="float-right">
                    <button class="inline-btn">保存</button>
                </div>
            </div>
            {% include note/component/note_path.html %}
        </div>

        <!-- note-edit-body -->
        <div class="col-md-12 note-edit-body">
            <span id="result" style="color:green"></span>
            <div class="col-md-12 toolbox">
                <input type="button" id="insertCode" class="toolbox-btn" value="代码" />
                <input type="button" id="insertStrong" class="toolbox-btn" value="加粗" />
                <input type="button" id="insertDel" class="toolbox-btn" value="删除线" />
                <input type="file" id="file" name="file" class="hide" />
                <input type="button" id="uploadBtn" class="toolbox-btn" value="文件" />
                <input type="button" class="toolbox-btn btn-primary" onclick="togglePreview(this)" value="预览" />
                <span id="uploadProgress" class="upload-progress"></span>
                <span id="autosaveResult" class="hide">自动保存成功</span>
            </div>

            <div class="col-md-12" id="editor-area">
                <div class="col-md-12">
                    <div id="edit-div">
                        <input style="display:none" name="id" value="{{file.id}}" />
                        <input type="text" name="version" value="{{file.version}}" class="hide" />
                        <input type="text" name="type" value="md" class="hide" />
                    </div>
                </div>

                <div class="col-md-12">
                    <div id="editor" class="col-md-12" style="height: auto; ">
                        <div id="markdown-input-div" class="col-md-12">
                            <textarea id="markdown-input" class="form-control" name="content" rows=50>{{file.content}}</textarea>
                        </div>

                        <div id="markdown-output-div" class="col-md-6 hide"></div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript">
    function codeInsert(code) {
        codeMirror.replaceSelection(code, 'around');
    }

    function initMdCodeMirror() {
        if (window.codeMirror) {
            return;
        }
        var height = Math.max(500, $("#markdown-output-div").height());
        var editor = $("#markdown-input")[0];

        if ($("#markdown-input").text() == "") {
            $("#markdown-input").text("\n\n\n\n\n");
        }

        window.codeMirror = initCodeMirror("#markdown-input", {
            mode: "text/x-markdown",
            height: "auto"
        });
    }

    function edit() {
        var clientWidth = document.body.clientWidth;
        if (clientWidth < 500) {
            // 移动端CodeMirror支持不佳，经常无法触发光标
            // simpleEdit();
            // 部分功能必须依赖CodeMirror
            mobileEdit();
            return;
        } else if (clientWidth < 1000) {
            // 至少需要500px方便编写
            mobileEdit();
            return;
        }
        initMdCodeMirror();
    }

    /**
     * 使用textarea编辑，对于CodeMirror支持不好的场景下使用
     */
    function simpleEdit() {
        $("#markdown-input-div").removeClass("hide").addClass("col-md-12");
        $("#markdown-output-div").removeClass("col-md-12").addClass("hide");
        var height = Math.max(500, $("#markdown-output-div").height());
        $("#markdown-input").css({ height: height + "px" });
        $("#edit-div").show();
        $("#edit-btns").hide();
    }

    function mobileEdit() {
        $("#markdown-input-div").removeClass("hide").addClass("col-md-12");
        $("#markdown-output-div").removeClass("col-md-12").addClass("hide");
        var height = Math.max(500, $("#markdown-output-div").height());
        $("#markdown-input").css({ height: height + "px" });
        $("#edit-div").show();
        $("#edit-btns").hide();
        initMdCodeMirror();
    }

    function togglePreview(target) {
        if ($("#markdown-input-div").hasClass("col-md-12")) {
            // 全屏模式
            $("#markdown-input-div").addClass("col-md-6").removeClass("col-md-12");
            $("#markdown-output-div").removeClass("hide");
            $(target).val("关闭预览");
        } else {
            // 半屏模式
            $("#markdown-input-div").removeClass("col-md-6").addClass("col-md-12");
            $("#markdown-output-div").addClass("hide");
            $(target).val("预览");
        }
        // 重新初始化codeMirror
        codeMirror.setSize("auto", "auto");
    }

    function escape(html, encode) {
        return html
            .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/\n/g, '<br/>')
            .replace(/ /g, '&nbsp;');
    }

    $(document).ready(function () {
        var oldContent = $("#markdown-input").val();
        var lastSaved = $("#markdown-input").val();
        var fileId = $("#fileId").text();
        var updatePreviewIntervalId = null;

        function contentUnchanged() {
            var input = $("#markdown-input").val();
            return input == oldContent;
        }

        function updatePreview() {
            var input = $("#markdown-input").val();
            
            if (contentUnchanged()) {
                return;
            }

            if ($("#markdown-output-div").hasClass("hide")) {
                return;
            }
            oldContent = input;
            var outtext = marked.parse(input);
            $("#markdown-output-div").html(outtext);
            $("#markdown-output-div").height($("#editor").height());
        }

        function autoSave() {
            var input = $("#markdown-input").val();
            // not modified
            if (input == lastSaved) {
                return;
            }
            lastSaved = input;
            $.post("/note/save", { id: fileId, content: input }, function (resp) {
                console.log(resp);
                if (resp.code == "success") {
                    $("#autosaveResult").show().fadeOut(1000);
                }
            })
        }

        updatePreview();
        edit();

        updatePreviewIntervalId = setInterval(updatePreview, 200);
        // setInterval(autoSave, 1000*30);

        $("#insertCode").on("click", function () {
            var selection = codeMirror.getSelection();
            if (selection != "" && selection != null) {
                if (selection.indexOf('\n') >= 0) {
                    codeMirror.replaceSelection("```" + selection + "```", "around");
                } else {
                    codeMirror.replaceSelection("`" + selection + "`", "around");
                }
            } else {
                codeInsert("```\n[代码]\n```");
            }
        });

        function toggleSurround(chars) {
            var selection = codeMirror.getSelection();
            if (selection.startsWith(chars) && selection.endsWith(chars)) {
                codeMirror.replaceSelection(selection.substring(chars.length, selection.length - chars.length), "around");
            } else {
                codeMirror.replaceSelection(chars + selection + chars, "around");
            }
        }

        $("#insertStrong").on("click", function () {
            toggleSurround("**");
        });

        $("#insertDel").click(function () {
            toggleSurround("~~");
        })

        $("#formatTable").click(function () {
            // var selection = codeMirror.getSelection();
            var selection = codeMirror.doc.getValue();
            var formatedText = formatMarkdownTable(selection);
            console.log(formatedText);
            // codeMirror.replaceSelection(formatedText, "around");
            codeMirror.doc.setValue(formatedText);
        });

        // 文件上传
        $("#uploadBtn").click(function () {
            xnote.requestUpload("#file", false, function (resp) {
                var fileLink = resp.link;
                codeInsert(fileLink);
            });
        });

        // 通过剪切板上传
        $(document).on("paste", function (e) {
            xnote.requestUploadByClip(e, 'N' + fileId, function (respJson) {
                console.log(respJson);
                var link = respJson.link;
                codeInsert(link);
            });
        });

        adjustHeight("#editor-area", 30);

        window.SUBMIT_FORM = false;

        $("#mainFrame").on("submit", function (e) {
            console.log(e);
            window.SUBMIT_FORM = true;
        });

        // 退出确认的询问
        window.onbeforeunload=function(e){
            if (contentUnchanged()) {
                return;
            }
            if (window.SUBMIT_FORM) {
                console.log("form is submit");
                return;
            }
            var e = window.event||e;  
            e.returnValue = "确定离开当前页面吗？";
        };
    });

</script>

<!-- GROUPS: {{file.groups}} -->
{% end %}